import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:simple_app/common/api.dart';
import 'package:simple_app/common/global.dart';
import 'package:simple_app/common/message/relay.dart';
import 'package:simple_app/common/model/chatMessage.dart';

class ChatRouteArgs {
  final String name;
  final String id;
  ChatRouteArgs({required this.name, required this.id});
}

class Chat extends StatefulWidget {
  const Chat({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _ChatState();
}

class _ChatState extends State<Chat> {
  var listenid = -1;

  Future<void> getList(String friendid) async {
    var res = await Api().chatMessageList(friendid);
    if (res.statusCode != 200) {
      return;
    }
    var jsonobj = jsonDecode(res.body);
    List<dynamic> list2 = jsonobj['list'];
    List<ChatMessage> newlist = [];
    for (var j in list2) {
      newlist.insert(0,ChatMessage.fromJson(j));
    }
    for (var n in list) {
      newlist.insert(0,n);
    }
    
    setState(() {
      list = newlist;
      itemCount = newlist.length;
    });
  }

  List<ChatMessage> list = [];
  var itemCount = 0;

  bool init = true;

  @override
  void initState() {
    super.initState();
    if (listenid == -1) {
      listenid = Global.listenMessage(receiveMessage);
    }
  }

  @override
  void dispose() {
    super.dispose();
    if (listenid != -1) {
      Global.removeListenMessage(listenid);
    }
  }

  final chatTxtBox = TextEditingController();

  String name = '';

  //当前聊天对象id
  String id = '';

  void receiveMessage(jsonobj) {
    if (jsonobj['type'] == "relay") {
      var data = Relay.fromJson(jsonobj);
      setState(() {
        list.insert(0,ChatMessage(
            sender: data.sender,
            receiver: data.receiver,
            msg: data.data,
            isRead: 1,
            addTime: DateTime.now().toString()));
        itemCount = list.length;
      });
      setState(() {
        if (list.length > 200) {
          list.removeAt(0);
        }
      });
      //滚动至底部
      Timer(const Duration(microseconds: 200), () {
        scrollController.jumpTo(0.0);
        // scrollController.jumpTo(scrollController.position.maxScrollExtent);
      });
    }
  }

  void sendMessage() {
    var msg = chatTxtBox.text;
    if (msg == '') {
      return;
    }
    var senderid = Api.userInfo.id;
    setState(() {
      list.insert(0,ChatMessage(
          sender: senderid,
          receiver: id,
          msg: msg,
          isRead: 1,
          addTime: DateTime.now().toString()));
      itemCount = list.length;
      if (list.length > 200) {
        list.removeAt(0);
      }
      //滚动至底部
      Timer(const Duration(microseconds: 200), () {
        scrollController.jumpTo(0.0);
        // scrollController.jumpTo(scrollController.position.maxScrollExtent);
      });
    });

    Global.sendMessage(Relay(msg, receiver: id, sender: senderid));

    chatTxtBox.text = '';
  }

  //滚动控制器
  var scrollController = ScrollController();

  Widget chatItem(ChatMessage msg) {
    if (msg.receiver == id) {
      //send

      // return Container(
      //   decoration: BoxDecoration(borderRadius: BorderRadius.circular(8),color: Color.fromARGB(255, r, g, b)),
      // );

      return Container(
        margin: const EdgeInsets.fromLTRB(0, 8, 0, 8),
        child: Stack(alignment: Alignment.topRight, children: [
          Container(
            margin: const EdgeInsets.fromLTRB(0, 0, 10, 0),
            constraints: BoxConstraints(maxWidth: chatWidth),
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                color: const Color(
                    0xff3f85ff)), //const Color.fromARGB(255, 255, 255, 255)),
            child: Text(
              msg.msg,
              softWrap: true,
              style: const TextStyle(color: Color(0xffffffff)),
            ),
          ),
          const Positioned(
            right: -10,
            top: 0,
            child: Icon(
              Icons.arrow_right,
              color: Color(0xff3f85ff),
              size: 36,
            ),
          )
        ]),
      );

      // return Container(
      //   margin: const EdgeInsets.fromLTRB(0, 8, 0, 8),
      //   child: Row(children: [
      //     const Icon(Icons.arrow_upward),
      //     Text(
      //       msg.msg,
      //       style: const TextStyle(color: Color.fromARGB(255, 0, 153, 255)),
      //     )
      //   ]),
      // );

    } else {
      return Container(
          margin: const EdgeInsets.fromLTRB(0, 8, 0, 8),
          child: Stack(children: [
            Container(
              margin: const EdgeInsets.fromLTRB(10, 0, 0, 0),
              constraints: BoxConstraints(maxWidth: chatWidth),
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  color: const Color.fromARGB(255, 255, 255, 255)),
              child: Text(
                msg.msg,
                softWrap: true,
              ),
            ),
            const Positioned(
              left: -10,
              top: 0,
              child: Icon(
                Icons.arrow_left,
                color: Color.fromARGB(255, 255, 255, 255),
                size: 36,
              ),
            )
          ]));

      // return Container(
      //   margin: const EdgeInsets.fromLTRB(0, 8, 0, 8),
      //   child: Row(children: [
      //     const Icon(Icons.arrow_downward),
      //     Text(
      //       msg.msg,
      //       style: const TextStyle(color: Color.fromARGB(255, 255, 196, 0)),
      //     )
      //   ]),
      // );
      //recv
    }
  }

  //初始最小值
  double chatWidth = 300 - 24;

  @override
  Widget build(BuildContext context) {
    chatWidth = MediaQuery.of(context).size.width - (24 * 2);

    var args = ModalRoute.of(context)!.settings.arguments as ChatRouteArgs?;
    if (args.runtimeType != Null) {
      name = args!.name;
      id = args.id;
    }
    if (init) {
      getList(id).then((v) {
        Timer(const Duration(microseconds: 300), () {
          scrollController.jumpTo(0.0);
          // scrollController.jumpTo(scrollController.position.maxScrollExtent);
        });
      });

      init = false;
    }
    return Scaffold(
      backgroundColor: const Color.fromARGB(255, 229, 233, 238),
      appBar: AppBar(
        title: Text(name),
      ),
      body: Column(
        children: [
          Expanded(
              child: ListView.builder(
                  reverse: true,
                  controller: scrollController,
                  addRepaintBoundaries: false,
                  addAutomaticKeepAlives: false,
                  itemCount: itemCount,
                  itemBuilder: (ctx, index) {
                    return chatItem(list[index]);
                  })),
          Container(
            decoration:
                const BoxDecoration(color: Color.fromARGB(255, 255, 255, 255)),
            child: Row(
              children: [
                Expanded(
                    child: TextFormField(
                  decoration: const InputDecoration(
                    contentPadding: EdgeInsets.fromLTRB(8, 0, 8, 0),
                    focusedBorder: InputBorder.none,
                    enabledBorder: InputBorder.none,
                    errorBorder: InputBorder.none,
                    disabledBorder: InputBorder.none,
                  ),
                  controller: chatTxtBox,
                )),
                GestureDetector(
                  onTap: sendMessage,
                  child: Container(
                    padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
                    child: const Icon(Icons.send),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}
